﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using FreeSql;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using XKPlatform.Common;
using XKPlatform.Common.Enums;
using XKPlatform.DataModels.Dao.BaseDao;
using XKPlatform.DataModels.Dao.BaseEntity;
using XKPlatform.DataModels.DBHelper;
using XKPlatform.DataModels.ReturnModel;
using XKPlatform.IService;

namespace XKPlatform.Controllers.SysController
{
    [Route("[controller]/[action]")]
    public class AutoTestController : BaseController
    {
        private readonly IAutoTestService _iservice;
        public AutoTestController(IAutoTestService iservice, IHttpContextAccessor httpContext) : base(httpContext)
        {
            _iservice = iservice;
        }
        /// <summary>
        /// 查询获取数据
        /// </summary>
        /// <param name="searchModel">查询参数</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetList([FromBody] AutoTestSearchParams search)
        {
            PageInfo pageinfo = new PageInfo();
            pageinfo.PageIndex = search.Page;
            pageinfo.PageSize = search.Limit;
            pageinfo.IsPaging = true;
            long count = 0;

            List<SortInfo<AutoTest, object>> sorLst = new List<SortInfo<AutoTest, object>>();
            SortInfo<AutoTest, object> sorItem = new SortInfo<AutoTest, object>();
            sorItem.SortMethods = SortEnum.Desc;
            //#注：默认按创建时间倒叙，如果有自定义排序规则修改此处
            sorItem.Orderby = o => o.CreatedOn;
            sorLst.Add(sorItem);
            Expression<Func<AutoTest, bool>> where = o => 1 == 1;
            //组装查询条件

            if (!string.IsNullOrWhiteSpace(search.UserName))
            {
                where = where.And(o => o.UserName == search.UserName);
            }

            if (!string.IsNullOrWhiteSpace(search.Title))
            {
                where = where.And(o => o.Title.Contains(search.Title));
            }
             
           

            var ret = _iservice.GetListByTbName(where, "AutoTest", sorLst, pageinfo);
            count = ret.count;
            var list = ret.list;

            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success), data = list, count = Convert.ToInt32(count) });

        }
        /// <summary>
        /// 新增或修改
        /// </summary>
        /// <param name="save"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveOrEdit([FromBody] AutoTest save)
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("UserNo", "123456");
            dic.Add("UserName", "dadads");

            DataType DbType = EnumHelper.StringConvertToEnum<DataType>(StaticClass.DbTypeStr ?? "SqlServer");


            var dd = _iservice.UpdateBySets(o => o.ID == save.ID).Set(a => a.UserName == "ceshi").Set(a => a.IPAddress == "12222").ExecuteAffrows();

            //判断主键为空 则是新增
            if (string.IsNullOrEmpty(save.ID))
            {
                //#补充主键 创建信息 
                save.ID = Guid.NewGuid().ToString();
                save.CreatedBy = userInfo.UserName;
                save.CreatedOn = DateTime.Now.ToString("yyyy-MM-dd:HH:mm:ss");
                _iservice.AddModel(save);
            }
            else
            {
                save.ModifyBy = userInfo.UserName;
                save.ModifyOn = DateTime.Now.ToString("yyyy-MM-dd:HH:mm:ss");
                //#注：忽略更新的列可以继续在 new{ o.CreatedBy,o.CreatedOn} 中追加
                _iservice.UpdateModel(save, o => o.ID == save.ID, o => new { o.CreatedBy, o.CreatedOn });
            }

            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success) });

        }
        /// <summary>
        /// 根据主键删除数据
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult Delete(string ID)
        {
            if (_iservice.Delete(o => o.ID == ID))
            {
                return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success) });
            }
            else
            {
                return Json(new BasePageModel { code = (int)MsgCodeEnum.Failed, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Failed) });

            }
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ExportExcel([FromBody] AutoTestSearchParams search)
        {

            Expression<Func<AutoTest, bool>> where = o => 1 == 1;
            //组装查询条件

            if (!string.IsNullOrWhiteSpace(search.UserName))
            {
                where = where.And(o => o.UserName == search.UserName);
            }

            if (!string.IsNullOrWhiteSpace(search.Title))
            {
                where = where.And(o => o.Title.Contains(search.Title));
            }


            (List<AutoTest> list, long count) list = _iservice.GetList(where);

            if (!list.Item1.Any())
            {
                return Json(new { code = 0, msg = "", data = "" });
            }

            string fileName = "Excel导出" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";

            string savePath = "wwwroot/files/Excel";//相对路径
            string path = "files/Excel/" + fileName;//文件返回地址，出错就返回错误信息。
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();  //开始监视代码运行时间
            string msg = "";
            bool b = OfficeHelper.ModelExportEPPlusExcel(list.Item1, savePath, fileName, ref msg);
            TimeSpan timespan = watch.Elapsed;  //获取当前实例测量得出的总时间
            watch.Stop();  //停止监视

            return Json(new { code = 0, msg = "导出成功！", data = path, timeSeconds = timespan.TotalSeconds });
        }


        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DelAll([FromBody] List<string> ids)
        {
            foreach (var item in ids)
            {
                AutoTest model = _iservice.GetModel(t => t.ID == item);
                if (model == null)
                {
                    continue;
                }
                List<string> sqls = new List<string>();
                sqls.Add($"DELETE FROM AutoTest where ID ='{model.ID}';");

                SqlHelper.ExecuteSqlTran(sqls);
            }

            return Json(new BasePageModel { code = (int)MsgCodeEnum.Success, msg = EnumUtils.GetEnumDesc(MsgCodeEnum.Success) });
        }
    }
}
